import axios from 'axios';

import { resResolve, resReject, reqResolve, reqReject } from './interceptors';
import network from '@/config/modules/network';
const { baseURL, timeout, formatDate, ignoreCancelToken, joinTime, joinParamsToUrl, contentType } = network;

export function createAxios(options = {}) {
	const defaultOptions = {
		baseURL: baseURL,
		timeout: timeout,
		headers: { 'content-Type': contentType },
		requestOptions: {
			// 是否返回原生响应头 比如：需要获取响应头时使用该属性
			isReturnNativeResponse: false,
			// 需要对返回数据进行处理
			isTransformResponse: true,
			// post请求的时候添加参数到url
			joinParamsToUrl,
			// 格式化提交参数时间
			formatDate,
			// 消息提示类型
			errorMessageMode: 'message',
			//  是否加入时间戳
			joinTime,
			// 忽略重复请求
			ignoreCancelToken,
			// 重试
			retryRequest: {
				isOpenRetry: true,
				count: 5,
				waitTime: 100,
			},
		},
	};
	return axios.create({
		...defaultOptions,
		...options,
	});
}

function createService(options = {}) {
	const service = createAxios(options);
	service.interceptors.request.use(reqResolve, reqReject);
	service.interceptors.response.use(resResolve, resReject);
	return service;
}

export const defAxios = createService();

export const uploadAxios = createService({
	timeout: 0,
	headers: {
		'Content-Type': 'multipart/form-data',
	},
});

export const defService = function () {
	const service = createAxios({
		timeout: 0,
	});
	service.interceptors.request.use(reqResolve, reqReject);
	return service;
};
